package com.fei.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fei.yygh.hosp.repository.HospitalRepository;
import com.fei.yygh.hosp.service.HospitalService;
import com.fei.yygh.model.hosp.Hospital;
import com.fei.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class HospitalServicImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;

    //添加或者更新
    @Override
    public void save(Map<String, Object> objectMap) {
        //将map数据转化为Hospital对象形式，先转化为字符串形式才能再转化为对象形式
        String jsonString = JSONObject.toJSONString(objectMap);
        Hospital hospital = JSONObject.parseObject(jsonString, Hospital.class);

        //判断是否存在数据，不存在就添加，存在就更新
        String hoscode = hospital.getHoscode();
        Hospital hospitalByHoscode = hospitalRepository.getHospitalByHoscode(hoscode);

        //存在，进行修改操作
        if (hospitalByHoscode != null) {
            hospital.setStatus(hospitalByHoscode.getStatus());
            hospital.setCreateTime(hospitalByHoscode.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }else {//不存在，进行添加操作
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }

    }

    //根据医院编号查询
    @Override
    public Hospital getByHospital(String hospital) {
        Hospital hospitalByHospital = hospitalRepository.getHospitalByHoscode(hospital);
        return hospitalByHospital;
    }

    //医院的分页查询（该查询为经典的MongnDB查询方法）
    @Override
    public Page selectHosPage(int page, int limit, HospitalQueryVo hospitalQueryVo) {
        Pageable pageable = PageRequest.of(page, limit);
        //创建条件适配器
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);// withIgnoreCase 为true表示查询不区分大小写
        //将ov对象转换为hospital对象
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        //创建对象
        Example<Hospital> example = Example.of(hospital, exampleMatcher);
        //调用方法进行查询
       Page<Hospital> all = hospitalRepository.findAll(example, pageable);
        return all;
    }


}
